package ex01.pyrmont;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author minly
 * @date 2021年08月04日15:32
 */
public class Response {

    private static final int BUFFER_SIZE = 1024;

    Request request;

    OutputStream output;

    public Response(OutputStream output) {
        this.output = output;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    public void sendStaticResource() throws IOException {
        byte[] bytes = new byte[BUFFER_SIZE];
        FileReader fileReader = null;
//        FileInputStream fis = null;
        try {
//            byte[] bytes = new byte[BUFFER_SIZE];
            File file = new File(HttpServer.WEB_ROOT, request.getUri());
            if (file.exists()) {
//                fis = new FileInputStream(file);
                fileReader = new FileReader(file);
                StringBuffer msg = new StringBuffer("HTTP/1.1 200\r\n" +
                        "Content-Type: text/html\r\n" +
                        "Content-Length: 25\r\n" +
                        "\r\n" );
                int rnt = fileReader.read();
                while (rnt != -1) {
                    msg.append((char)rnt);
                    rnt = fileReader.read();
                }
                output.write(msg.toString().getBytes(StandardCharsets.UTF_8));

            } else {
                String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
                        "Content-Type: text/html\r\n" +
                        "Content-Length: 25\r\n" +
                        "\r\n" +
                        "<h1>File Not Found</h1>";
                output.write(errorMessage.getBytes(StandardCharsets.UTF_8));
            }
            output.flush();
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
           if (fileReader != null) {
               fileReader.close();
           }
        }
    }

    public static void main(String[] args) {
        System.out.println("1".getBytes(StandardCharsets.UTF_8));
    }
}
